<template>
	<view>
		<mine-head title="健康监测"></mine-head>
		<view class="content">
			<view class="subTitle _df">
				健康检测间隔
			</view>
			<!-- <view class="tip">
				注：手表检测期间不要设置检测间隔，会导致数据同步失败。
			</view> -->
			<view class="item" @click="showPop(1)">
				<view class="right fr">
					每{{params.frequency}}分钟一次<u-icon class="ml20" name="arrow-right" color="#666" size="26"></u-icon>
				</view>
				<view class="text">
					<view class="title">
						全天健康检测
					</view>
					<view class="info">
						检测间隔越低，数据越详细，但手机和手表电量消耗越快。
					</view>
				</view>
			</view>
			
			<view class="subTitle">
				心率设置
			</view>
			<view class="item" @click="showPop(2)">
				<view class="right fr">
					{{params.high}}次/分钟<u-icon class="ml20" name="arrow-right" color="#666" size="26"></u-icon>
				</view>
				<view class="text">
					<view class="title">
						心率过高提醒
					</view>
					<view class="info">
						非活跃状态下，若心率持续高于预警值，设备将会进行提醒。
					</view>
				</view>
				
			</view>
			<view class="item" @click="showPop(3)">
				<view class="right fr">
					{{params.low}}次/分钟<u-icon class="ml20" name="arrow-right" color="#666" size="26"></u-icon>
				</view>
				<view class="text">
					<view class="title">
						心率过低提醒
					</view>
					<view class="info">
						非活跃状态下，若心率持续低于预警值，设备将会进行提醒。
					</view>
				</view>
				
			</view>
			<view class="item" @click="showPop(4)">
				<view class="right fr">
					{{params.sensitiveData==1?'低':params.sensitiveData==2?'中':'高'}}<u-icon class="ml20" name="arrow-right" color="#666" size="26"></u-icon>
				</view>
				<view class="text">
					<view class="title">
						预警敏感值
					</view>
					<view class="info">
						敏感值越高，手表提醒频率越高。
					</view>
				</view>
				
			</view>
			<!-- <view class="h40"></view> -->
			<!-- <view class="subTitle">
				睡眠设置
			</view>
			<view class="item">
				<view class="right fr">
					<u-switch v-model="sleepVal" size="50" active-color="#6387FF" inactive-color="#eee"></u-switch>
				</view>
				<view class="text">
					<view class="title">
						睡眠高精度监测
					</view>
					<view class="info">
						在睡眠期间，会通过开启心率传感器进行连续监测，来跟踪快速眼动期分布，但设备续航时间将会严重减少
					</view>
				</view>
			</view> -->
			<view class="h40"></view>
			<view class="subTitle">
				血氧饱和度设置
			</view>
			<view class="item" @click="showPop(5)">
				<view class="right fr">
					{{params.oxygen}}%<u-icon class="ml20" name="arrow-right" color="#666" size="26"></u-icon>
				</view>
				<view class="text">
					<view class="title">
						血氧过低提醒
					</view>
					<view class="info">
						非睡眠状态下，检测到血氧在一定时间内低于提醒值时设备端弹出提醒。
					</view>
				</view>
			</view>
			<view class="h40"></view>
			<view class="subTitle">
				压力设置
			</view>
			<view class="item" @click="showPop(6)">
				<view class="right fr">
					{{params.relax}}<u-icon class="ml20" name="arrow-right" color="#666" size="26"></u-icon>
				</view>
				<view class="text">
					<view class="title">
						放松提醒
					</view>
					<view class="info">
						在非睡眠安静状态下，检测到压力值在一定时间内高于{{params.relax}}时，手表将会提醒。
					</view>
				</view>
			</view>
			<view class="h40"></view>
			<view class="subTitle">
				情绪提醒设置
			</view>
			<view class="item" @click="showPop(7)">
				<view class="right fr">
					{{emotionData}}<u-icon class="ml20" name="arrow-right" color="#666" size="26"></u-icon>
				</view>
				<view class="text">
					<view class="title">
						情绪异常提醒
					</view>
					<view class="info">
						检测到情绪为{{emotionData}}时，手表将会提醒。
					</view>
				</view>
			</view>
		</view>
		<!-- <send-order ref="blue" @blueBack="blueBack"></send-order> -->
		<u-select :title="selectTitle" v-model="actionShow" :default-value="defaultValue" :list="options" @confirm="confirm"></u-select>
		<!-- <u-select v-model="actionShow" label-name="text" :default-value="defaultValue" value-name="value" :list="options" @confirm="confirm"></u-select> -->
		<!-- <u-picker v-model="actionShow" range-key="text" mode="selector" :range="options" confirm-color="#FF4651" @confirm="confirm"></u-picker> -->
	</view>
</template>

<script>
	let timer
	export default {
		data() {
			return {
				heartVal1:'10分钟',
				heartVal2:'150次',
				heartVal3:'60次',
				heartVal4:'高',
				sleepVal:true,
				xueyangVal:'80%',
				yaliVal:true,
				actionShow:false,
				options:[],
				options5:[],
				options6:[],
				params:{
					frequency:null,//心率检测频率
					high:null,//心率过高
					low:null,//心率过低
					sensitiveData:null,//心率敏感值
					oxygen:null,//血氧过低
					relax:null,//压力提醒
					emotionData:null,//压力提醒
					
				},
				emotionData:'',
				relaxData:'',
				defaultValue:[],
				selectTitle:'',
				type:1,
				deviceId:'',
				notifyUuid:'',
				serviceId:'',
				writeId:'',
				isJoin:false
			};
		},
		onLoad() {
			
		},
		onShow() {
			this.getOptions()
			this.getWatch()
		},
		methods:{
			getWatch(){
				let that = this;
				uni.$_get({
					url: "get-watch",
					that: that,
					success(res) {
						if(res.code == 0){
							let _data = res.data;
							console.log(_data)
							if(_data){
								that.deviceId = _data.deviceId
								that.notifyUuid = _data.notifyUuid
								that.serviceId = _data.serviceId
								that.writeId = _data.writeId
							}else{
								uni.showToast({
									title:'请连接手表！',
									icon:'none'
								})
							}
						}
						
					},
					fail(err) {
						
					},
				});
			},
			blueBack(e,ids){
				if(ids){
					this.deviceId = ids.deviceId
					this.notifyUuid = ids.notifyUuid
					this.serviceId = ids.serviceId
					this.writeId = ids.writeId
				}
				this.isJoin = e
				if(e){
					//设置心率检测间隔和范围指令0x31
					// let order = 'da3106000001173b' + this.page.frequency.toString(16) + '50'
					// setTimeout(()=>{
					// 	this.writeFn(order)
					// },1000)
				}else{
					// uni.showToast({
					// 	title:'请连接手表',
					// 	icon:'none'
					// })
					this.$refs.blue.getWatch()
				}
			},
			writeFn(orderVal) {
				var that = this
				let crc = uni.$_getCrc_16_ibm(orderVal)
				let val = orderVal + crc
				console.log(val, '发送的指令')
				let buff = uni.$_hexStringToArrayBuffer(val)
				uni.writeBLECharacteristicValue({
					// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: that.serviceId,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: that.writeId, //第二步写入的特征值
					// 这里的value是ArrayBuffer类型
					value: buff,
					success: function(res) {
						//此时设备已接收到你写入的数据
						console.log("写入成功", res)
						uni.onBLECharacteristicValueChange(result => {
							// console.log("监听低功耗蓝牙设备的特征值变化", result);
							if (result.value) {
								let resHex = uni.$_ab2hex(result.value)
								console.log('设备返回原始数据', resHex)
								// uni.hideLoading()
								clearInterval(timer)
								uni.showToast({
									title:'设置成功',
									icon:'none'
								})
								that.addData()
								// that.dataObj = uni.$_parse_blue_response(resHex, 2)
							}else{
								
							}
						})
						// that.startNotice()
					},
					fail: function(err) {
						console.log(err)
						// uni.hideLoading()
						that.$refs.blue.getWatch()
					},
					// complete: function() {
					// 	console.log("调用结束");
					// }
				})
			},
			
			//订阅蓝牙消息返回
			startNotice() {
				var that = this;
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
					deviceId: this.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: this.serviceId,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: this.notifyUuid, //第一步 开启监听 notityid  第二步发送指令 write
					success(res) {
						//接收蓝牙返回消息
						// that.listenValueChange()
						
					},
					fail(err) {
						console.log(err)
						uni.hideLoading()
					}
				})
			},
			getHeartSet(){
				let that = this
				uni.$_get({
					url: "getHeartSet",
					that: that,
					success(res) {
						console.log(res)
						let _data = res.data;
						if(res.code == 0){
							that.params = _data
							that.emotionData = that.options6.find(item =>item.valueData == _data.emotionData).name
						}else{
							uni.showToast({
								title: res.msg,
								duration: 2000,
								icon:'error'
							});
						}
					},
					fail(err) {
						uni.showToast({
							title: err.msg,
							duration: 1000,
							icon:'error'
						});	
					},
				});
			},
			addData(){
				let that = this
				let page = {
					pastFrequency:this.params.pastFrequency,//检测频率old
					frequency:this.params.frequency,//心率检测频率
					high:this.params.high,//心率过高
					low:this.params.low,//心率过低
					sensitiveData:this.params.sensitiveData,//心率敏感值
					oxygen:this.params.oxygen,//血氧过低
					relax:this.params.relax,//压力提醒
					emotionData:this.params.emotionData,//压力提醒
				}
				uni.$_post({
					url: "heartSetAddOrUpdate",
					that: that,
					params: page,
					success(res) {
						console.log(res)
						if(res.code == 0){
						}else{
							uni.showToast({
								title: res.msg,
								duration: 2000,
								icon:'error'
							});
						}
					},
					fail(err) {
						uni.showToast({
							title: err.msg,
							duration: 1000,
							icon:'error'
						});	
					},
				});
			},
			getOptions(){
				let that = this
				let p = {
					data:'emotion_index'
				}
				uni.$_post({
					url: "getSystemDataDictionary",
					that: that,
					params: p,
					success(res) {
						console.log(res)
						if(res.code == 0){
							let arr = []
							res.data.map((item,index) =>{
								item.valueData = Number(item.valueData)
								if(index>2){
									arr.push(item)
								}
							})
							that.options6 = arr
							that.getHeartSet()
						}else{
							uni.showToast({
								title: res.msg,
								duration: 2000,
								icon:'error'
							});
						}
					},
					fail(err) {
						uni.showToast({
							title: err.msg,
							duration: 1000,
							icon:'error'
						});	
					},
				});
			},
			
			showPop(e){
				this.actionShow = true
				this.options = []
				this.defaultValue = []
				switch (e){
					case 1:
					this.type = 1
					this.selectTitle = '健康检测间隔'
					for(let i=3;i<=60;i++){
						let val = i
						let obj = {
							index:i - 3,
							value:val,
							label:String(val)
						}
						this.options.push(obj)
					}
					let index = this.options.find((item) => item.value==this.params.frequency).index
					this.defaultValue = [index]
					break
					case 2:
					this.type = 2 
					this.selectTitle = '心率过高提醒'
					for(let i=1;i<=40;i++){
						let val = i * 5
						let obj = {
							index:i,
							value:val,
							label:String(val)
						}
						this.options.push(obj)
					}
					let index2 = this.options.find((item) => item.value==this.params.high).index
					this.defaultValue = [index2-1]
					break 
					case 3:
					this.type = 3
					this.selectTitle = '心率过低提醒'
					for(let i=1;i<=40;i++){
						let val = i * 5
						let obj = {
							index:i,
							value:val,
							label:String(val)
						}
						this.options.push(obj)
					}
					let index3 = this.options.find((item) => item.value==this.params.low).index
					this.defaultValue = [index3-1]
					break
					case 4:
					this.type = 4
					this.selectTitle = '预警敏感值'
					this.options = [
						{
							index:1,
							value:1,
							label:'低'
						},
						{
							index:2,
							value:2,
							label:'中'
						},
						{
							index:3,
							value:3,
							label:'高'
						}
					]
					let index4 = this.options.find((item) => item.value==this.params.sensitiveData).index
					this.defaultValue = [index4-1]
					break 
					case 5:
					this.type = 5
					this.selectTitle = '血氧过低提醒'
					for(let i=1;i<=20;i++){
						let val = i * 5
						let obj = {
							index:i,
							value:val,
							label:String(val)
						}
						this.options.push(obj)
					}
					let index5 = this.options.find((item) => item.value==this.params.oxygen).index
					this.defaultValue = [index5-1]
					break
					case 6:
					this.type = 6
					this.selectTitle = '压力设置'
					for(let i=1;i<=100;i++){
						let val = i
						let obj = {
							index:i,
							value:val,
							label:String(val)
						}
						this.options.push(obj)
					}
					let index6 = this.options.find((item) => item.value==this.params.relax).index
					this.defaultValue = [index6-1]
					break
					case 7:
					this.type = 7
					this.selectTitle = '情绪设置'
					let arr = []
					this.options6.map((item,index) =>{
						let obj = {
							index:index+1,
							value:item.valueData,
							label:item.name
						}
						arr.push(obj)
					})
					
					this.options = arr
					let index7 = this.options.find((item) => item.value==this.params.emotionData).index
					this.defaultValue = [index7-1]
					break
				}
			},
			
			//全天心率监测
			confirm(e){
				console.log(e)
				switch (this.type){
					case 1:
					uni.showLoading({
						title: '设置中...'
					})
					this.params.frequency = e[0].value
					uni.setStorageSync('interval',this.params.frequency)
					let frequency = uni.$_padHexString(e[0].value,2)
					let order = 'da3106000001173b' + frequency.toString(16) + '50'
					timer = setInterval(() =>{
						this.writeFn(order)
					},1000)
					
					// setTimeout(()=>{
					// 	this.writeFn(order)
					// },1000)
					break
					case 2:
					this.params.high = e[0].value
					this.addData()
					break 
					case 3:
					this.params.low = e[0].value
					this.addData()
					break
					case 4:
					this.params.sensitiveData = e[0].value
					this.addData()
					break 
					case 5:
					this.params.oxygen = e[0].value
					this.addData()
					break 
					case 6:
					this.params.relax = e[0].value
					this.addData()
					break 
					case 7:
					this.params.emotionData = e[0].value
					this.emotionData = e[0].label
					this.addData()
					break 
				}
				
				
			},
			confirm2(e){
				// console.log(e)
				let i = e[0]
				if(this.type == 1){
					this.heartVal1 = this.options[i].text
					// this.heartVal1 = e[0].label
					// this.defaultValue = [e[0].value]
					
				}else if(this.type == 2){
					this.heartVal2 = this.options[i].text
					// this.heartVal2= e[0].label
					// this.defaultValue = [e[0].value]
				}
				else if(this.type == 5){
					this.xueyangVal = this.options[i].text
					// this.heartVal2= e[0].label
					// this.defaultValue = [e[0].value]
				}
				
				this.setData()
			},
			//更新数据
			setData(){
				
			}
		},
	}
</script>

<style lang="scss" scoped>
.content{
	padding: 60rpx 30rpx;
	.subTitle{
		font-size: 24rpx;
		color: #666;
		margin-bottom: 30rpx;
	}
	.item{
		margin-bottom: 40rpx;
		overflow: hidden;
		.text{
			padding-right: 80rpx;
			overflow: hidden;
			.title{
				font-size: 32rpx;
				color: #000;
				font-family: $uni-font-family-Bold;
				margin-bottom: 10rpx;
			}
			.info{
				font-size: 24rpx;
				color: #666;
				line-height: 30rpx;
			}
			
		}
		.right{
			font-size: 24rpx;
			color: #888;
			float: right;
			margin-top: 30rpx;
			// min-width: 150rpx;
			text-align: right;
		}
		
	}
	.tip{
		font-size: 26rpx;
		color: #f90;
		margin-bottom: 10rpx;
	}
}
</style>
